"""
用户 | 映射
"""

from functools import partial

from config import settings
from mapping.base_mapping import (
    MappingBase,
    get_field_map,
)
from models.po import (
    UserPO,
    UserTokenPO,
)
from models.vo import (
    UserAuthenticatedVO,
    UserDetailVO,
    UserListPage,
    UserListVO,
)
from utils.converter_utils import TimeConverter
from utils.data_utils.special import ObjectIdStr


def get_file_view_url(file_id: ObjectIdStr) -> str:
    """ 获取文件预览 URL """

    from main import app

    file_view_path: str = str(app.url_path_for("file_view", file_id=file_id))
    backend_url: str = settings.BACKEND.URL

    return backend_url + file_view_path


class UserMapping(MappingBase):
    """ 用户 | 映射 """

    id_field = "user_id"
    po = UserPO
    list_vo = UserListVO
    detail_vo = UserDetailVO
    vo_page = UserListPage

    list_mapping = {
        "avatar_url": get_field_map(["avatar_id"], func=get_file_view_url),
    }

    detail_mapping = {
        "last_active": get_field_map(["update_time"], func=TimeConverter.datetime_2_datetime_str),
        "join_date": get_field_map(["create_time"], func=partial(TimeConverter.datetime_str_2_date, to_string=True)),
    }

    @staticmethod
    def po_2_auth_vo(
        user_po: UserPO,
        user_token_po: UserTokenPO
    ) -> UserAuthenticatedVO:
        return UserAuthenticatedVO(
            **{
                **user_po.model_dump(),
                "avatar_url": get_file_view_url(user_po.avatar_id),
                "token": user_token_po.key,
                "user_id": user_po.id,
            },
        )
